<?php
	require_once('config.php');
	require_once('phpMailer/class.phpmailer.php');
	define('DB_ERROR', 'Database error: ');
	define('MAILER_ERROR', 'Mailer error: ');
	define('FILE_ACCESS_ERROR', 'File access error: ');
	define('OUTPUT_TYPE_ERROR', 'Output type error: ');
	function get_query_result($db_information, $log_file, $output_type, $output_file_name=''){
		// connect, and select database
		$db_link = mysql_connect($db_information['db_host'],$db_information['username'], $db_information['password']);
		if (!$db_link) {
		    error_log(date("d/m/y H:i:s") .  " | " . DB_ERROR . mysql_error($db_link) . "\n", 3, $log_file);
		    return false;
		}
		$db_selected = mysql_select_db($db_information['db_name'], $db_link);
		if (!$db_selected) {
		   error_log(date("d/m/y H:i:s") .  " | " . DB_ERROR . mysql_error($db_link) . "\n", 3, $log_file);
		   return false;
		}
		// fetch results from database
		$result = mysql_query($db_information['query']);
		if (!$result) {
		    error_log(date("d/m/y H:i:s") .  " | " . DB_ERROR . mysql_error($db_link) . "\n", 3, $log_file);
		    return false;
		}
		// convert results to the specified output type
		switch($output_type)
		{
			case 'plain':{
					$output_string = '';
					while($row = mysql_fetch_array($result, MYSQL_NUM)){
						for($i = 0; $i < count($row); $i++){
							 $output_string .= $row[$i] . "|";
						}
						$output_string .= "\n";
					}
					return $output_string;
				}
				break;
			case 'csv':{
					$tmp = fopen($output_file_name, "w+");
					if(!$tmp){
						error_log(date("d/m/y H:i:s") .  " | " . FILE_ACCESS_ERROR . $output_file_name . "\n", 3, $log_file);
						return false;
					}
					while($row = mysql_fetch_array($result, MYSQL_NUM)){
						fputcsv($tmp,$row);
					}
					fclose($tmp);
					return true;
				}
				break;
			default:{
					error_log(date("d/m/y H:i:s") .  " | " . OUTPUT_TYPE_ERROR . $output_type . "\n", 3, $log_file);
					return false;
				}
				break;
		}
	}

	function send_mail($agent, $content, $receivers, $mail_log_file, $file_to_attach){

		$mail             = new PHPMailer();
		$body             = $content;
		$mail->IsSMTP();
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$mail->SMTPDebug = $agent['smtp_debug'];   // debug the smtp server
		$mail->Host       = $agent['smtp_host'];      // sets GMAIL as the SMTP server
		$mail->Port       = $agent['smtp_port'];                   // set the SMTP port for the GMAIL server

		$mail->Username   = $agent['smtp_user'];  // GMAIL username
		$mail->Password   = $agent['smtp_pass'];  // GMAIL password

		$mail->From       = $agent['from'];
		$mail->FromName   = $agent['from_name'];
		$mail->Timeout	  = $agent['timeout'];
		$mail->Subject    = $agent['subject'];

		$mail->Body = $body;
		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
		$mail->WordWrap   = 50; // set word wrap

		for($i=0; $i< count($receivers); $i++){
			$mail->AddAddress($receivers[$i]['addr'],$receivers[$i]['name']);
		}

		$mail->AddAttachment($file_to_attach, "results.csv");
		$mail->IsHTML(true); // send as HTML
		//var_dump($mail); exit;
		if(!$mail->Send()) {
		  error_log(date("d/m/y H:i:s") .  " | " . MAILER_ERROR . $mail->ErrorInfo . "\n", 3, $mail_log_file);
		} else {
		  error_log(date("d/m/y H:i:s") .  " | " ."Mail sent \n", 3, $mail_log_file);
		}
	}

	if(!get_query_result($db_info, $log_file, 'csv', 'results.csv')){
		die("Can't get the query result, see $log_file for more detail");
	}else{
		$message = "File Dated: ". date('F d, Y') . " \n";
		send_mail($mail_agent, $message, $email_receivers, $log_file, 'results.csv');
		exit;
	}

?>